package com.qyc.interceptor;

import com.qyc.enums.CodeMsgEnum;
import com.qyc.exception.SystemException;
import com.qyc.utils.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @className: LoginCheckInterceptor
 * @Description: 登陆校验拦截器
 * @author: qinyc
 * @date: 2023/6/21 0:24
 * @version: v1.0
 */
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    /**
     * @Author qinyc
     * @Description  请求拦截
     * @version: v1.0
     * @Date 1:44 2023/6/21
     **/
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("已拦截："+request.getRequestURI());
        /*
         * 放行前要做的工作
         *  返回值是个布尔值，
         *      当布尔值返回true：放行
         *      当布尔值返回false：拦截
         */
        //判断是否为预请求，如果是预请求就直接放行
        if (request.getMethod().equals("OPTIONS")){
            //放行
            return true;
        }

        /*
         * 请求不是预请求
         */
        //从请求头中获取Token
        String token = request.getHeader("token");
        //判断请求头中是否有Token信息
        if (!StringUtils.hasText(token)){
            //token为空(用户未登录)
            throw new SystemException(CodeMsgEnum.USER_IS_NOT_LOGIN);
        }
        //判断Token合法性
        try {
            //解析Token
            JwtUtil.parseJWT(token);
        }catch (Exception exception){
            //解析Token失败，要么Token过期了，要么Token不合法（全局异常捕获返回统一异常响应，登录过期）
            throw new SystemException(CodeMsgEnum.LOGIN_IS_EXPIRED);
        }

        /*
         * 请求校验通过
         */
        //放行请求
        return true;
    }

    /**
     * @Author qinyc
     * @Description  响应拦截
     * @version: v1.0
     * @Date 1:43 2023/6/21
     **/
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * @Author qinyc
     * @Description  渲染视图之前做得工作
     * @version: v1.0
     * @Date 1:44 2023/6/21
     **/
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
